package com.lagou.homework.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: lizequn
 * @time: 2021/7/19 19:30
 * @description:
 */
@Configuration
public class MyRabbitConfig {

    // 定义正常交换机
    @Bean
    public Exchange exchange() {
        return new CustomExchange("ex.pay", ExchangeTypes.DIRECT, true, false);
    }

    // 定义死信交换机（也是普通的交换机）
    @Bean
    public Exchange dlExchange() {
        return new CustomExchange("dl.ex.pay", ExchangeTypes.DIRECT, true, false);
    }

    // 定义正常队列
    // 指明ttl过期时间
    // 要指明队列中的消息过期后要发送哪里去
    @Bean
    public Queue queue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-message-ttl", 10000); // 10秒超时
        arguments.put("x-dead-letter-exchange", "dl.ex.pay");
        arguments.put("x-dead-letter-routing-key", "dl.rk.key");

        return new Queue("queue.pay", true, false, false, arguments);
    }

    // 定义死信队列（也是正常队列）
    @Bean
    public Queue dlQueue() {
        return new Queue("dl.queue.pay", true, false, false, null);
    }

    // 绑定正常交换机正常队列
    @Bean
    public Binding binding() {
        Binding binding = BindingBuilder
                .bind(queue())
                .to(exchange())
                .with("rk.key")
                .noargs();
        return binding;
    }

    // 绑定死信交换机和死信队列
    @Bean
    public Binding dlBinding() {
        return BindingBuilder
                .bind(dlQueue())
                .to(dlExchange())
                .with("dl.rk.key")
                .noargs();
    }

    // 自动声明交换机和队列等
    @Bean
    @Autowired
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }
}
